package com.kfm.web.controller.system;

import com.kfm.common.domain.entity.Role;
import com.kfm.common.domain.response.Result;
import com.kfm.system.service.RolesService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RolesService rolesService;

    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('role:list') or hasAnyRole('ROLE_admin')")
    public Result list(Role role) {
        List<Role> roles = rolesService.selectByCondition(role);
        return roles.isEmpty()? Result.failure("没有查询到角色信息") : Result.success("查询成功", roles);
    }

    @PostMapping("/edit")
    @PreAuthorize("hasAuthority('role:edit') or hasAnyRole('ROLE_admin')")
    public Result edit(@RequestBody Role role) {
        int result = rolesService.updateByPrimaryKeySelective(role);
        return result == 0 ? Result.failure("修改失败") : Result.success("修改成功");
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('role:add') or hasAnyRole('ROLE_admin')")
    public Result add(@RequestBody Role role) {
        int result = rolesService.insertSelective(role);
        return result == 0 ? Result.failure("新增失败") : Result.success("新增成功");
    }

    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('role:delete') or hasAnyRole('ROLE_admin')")
    public Result remove(@PathVariable("id") Integer id) {
        int result = rolesService.deleteByPrimaryKey(id);
        return result == 0 ? Result.failure("删除失败") : Result.success("删除成功");
    }
}
